package com.iss.ljx.login.service.impl;


import com.iss.ljx.login.entity.LoginUserEntity;
import com.iss.ljx.login.entity.MenuLevelEntity;
import com.iss.ljx.mybatis.entity.PtMenuEntity;
import com.iss.ljx.mybatis.entity.PtUserEntity;
import com.iss.ljx.login.repository.LoginDao;
import com.iss.ljx.login.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service("loginService")
public class LoginServiceImpl implements LoginService {
    @Resource
    private LoginDao loginDao;
    @Override
    public PtUserEntity queryUserInfoByUserName(String username) {
        return loginDao.queryUserInfoByUserName(username);
    }
    @Override
    public List<String> queryRoleByID(String userUuid) {
        return loginDao.queryRoleByID(userUuid);
    }

    private Logger logger = LogManager.getLogger(this.getClass());
    @Override
    public List<MenuLevelEntity> queryMenuLevelList() {

        LoginUserEntity userDetails = (LoginUserEntity) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        String userUUID = userDetails.getUserUuid();
        String langId = LocaleContextHolder.getLocale().toString();
        List<PtMenuEntity> ptMenuEntityList = loginDao.queryMenuListByUserId(userUUID,langId);
        MenuLevelEntity menuLevel1;
        MenuLevelEntity menuLevel2;
        MenuLevelEntity menuLevel3;
        List<MenuLevelEntity> menuLevelList = new ArrayList<>();
        //level 1
        for(PtMenuEntity menu1:ptMenuEntityList){
            if(menu1.getMenuLevel() == 1){
                menuLevel1 = new MenuLevelEntity(menu1);
                menuLevelList.add(menuLevel1);
                //level 2
                for(PtMenuEntity menu2:ptMenuEntityList){
                    if(menu1.getMenuId() != null && menu1.getMenuId().equals(menu2.getParentId())){
                        menuLevel2 = new MenuLevelEntity(menu2);
                        menuLevel1.getChildrenList().add(menuLevel2);
                        //level 3
                        for(PtMenuEntity menu3:ptMenuEntityList){
                            if(menu2.getMenuId() != null && menu2.getMenuId().equals(menu3.getParentId())) {
                                menuLevel3 = new MenuLevelEntity(menu3);
                                menuLevel2.getChildrenList().add(menuLevel3);
                            }
                        }
                    }
                }
            }
        }
        //logger.info(menuLevelList);
        return menuLevelList;
    }
}
